﻿using System;
using OneWorks.Web.Extension;

namespace OneWorks.Web.Common
{
    using Application;
    using Application.Entity;
    using Application.Interface;
    using Metadata.Enum;
    using Model;
    using Metadata.Entity;

    public class UserHandle
    {
        private readonly IUserService _userService;


        static UserHandle()
        {
            AutoMapper.Mapper.CreateMap<User, UserModel>().ForMember(
                dto => dto.UserCode, opt => opt.MapFrom(o => o.ID));
            AutoMapper.Mapper.CreateMap<UserModel, User>();
            AutoMapper.Mapper.CreateMap<User, AccountModel>().ForMember(
                dto => dto.UserCode, opt => opt.MapFrom(o => o.ID));
            AutoMapper.Mapper.CreateMap<AccountModel, User>();
        }

        public UserHandle()
        {
            _userService = new UserService();
        }

        public RunResult<bool> Login(AccountModel model)
        {
            if (string.IsNullOrEmpty(model.Account))
                return new RunResult<bool>
                {
                    Status = ResultStatus.Failure,
                    Result = false,
                    Message = "用户名不能为空"
                };

            if (string.IsNullOrEmpty(model.PassWord))
                return new RunResult<bool>
                {
                    Status = ResultStatus.Failure,
                    Result = false,
                    Message = "密码不能为空"
                };

            RunResult<bool> runResult = _userService.Login(new User { Account = model.Account, PassWord = Utils.Tools.MD5(model.PassWord) });

            if (!runResult.Result)
                return new RunResult<bool>
                {
                    Status = ResultStatus.Failure,
                    Result = false,
                    Message = runResult.Message
                };

            //该账户存在,获取账户信息
            RunResult<User> result = _userService.Get(model.Account);

            if (result.Status != ResultStatus.Success)
                return new RunResult<bool>
                {
                    Status = ResultStatus.Failure,
                    Result = false,
                    Message = result.Message
                };

            UserModel userModel = AutoMapper.Mapper.Map<User, UserModel>(result.Result);

            if (userModel.ErrorCount >= 5)
            {
                _userService.ModifyErrorCount(userModel.UserCode, 0);
                _userService.LockUser(userModel.UserCode);
                return new RunResult<bool>
                {
                    Status = ResultStatus.Failure,
                    Result = false,
                    Message = "用户已锁定"
                };
            }

            var code = System.Web.HttpContext.Current.Session[Config.LOGINCODE];

            if (userModel.ErrorCount > 2 && (code == null || !String.Equals(code.ToString(), model.Captcha)))
            {
                _userService.ModifyErrorCount(userModel.UserCode, userModel.ErrorCount + 1);
                return new RunResult<bool>
                {
                    Status = ResultStatus.Failure,
                    Result = false,
                    Message = "验证码错误"
                };
            }

            if (runResult.Status == ResultStatus.Success)
            {
                _userService.ModifyErrorCount(userModel.UserCode, 0);
                _userService.ModifyLastLoginDate(userModel.UserCode);
                Cookie.SetCookie(Config.COOKIENAME,
                    Utils.Tools.DESEncrypt(userModel.UserCode.ToString().ToLower(), Config.COOKIEKEY), "/");
                return new RunResult<bool>
                {
                    Status = ResultStatus.Success,
                    Result = true,
                    Message = "登录成功"
                };
            }
            _userService.ModifyErrorCount(userModel.UserCode, userModel.ErrorCount + 1);
            return new RunResult<bool>
            {
                Result = false,
                Message = runResult.Message,
                Status = ResultStatus.Failure,
            };
        }

        public RunResult<UserModel> GetUserInfo(Guid guid)
        {
            RunResult<UserModel> result = new RunResult<UserModel>();

            RunResult<User> runResult = _userService.Get(guid);

            if (runResult.Status == ResultStatus.Success)
            {
                result.Status = runResult.Status;
                result.Result = AutoMapper.Mapper.Map<User, UserModel>(runResult.Result);
            }
            else
            {
                result.Status = runResult.Status;
                result.Message = runResult.Message;
                result.Exception = runResult.Exception;
            }
            return result;
        }

        public RunResult<UserModel> Create(AccountModel account)
        {
            User user = AutoMapper.Mapper.Map<AccountModel, User>(account);
            user.PassWord = Utils.Tools.MD5(user.PassWord);
            RunResult<User> runResult = _userService.Add(user);
            return new RunResult<UserModel>
                       {
                           Status = runResult.Status,
                           Exception = runResult.Exception,
                           Message = runResult.Message,
                           Result = AutoMapper.Mapper.Map<User, UserModel>(runResult.Result)
                       };
        }

        public bool ExistAccount(string value)
        {
            RunResult<bool> runResult = _userService.ExistAccount(value);
            return runResult.Status == ResultStatus.Success && runResult.Result;
        }

        public UserModel GetLoginStatus(string value)
        {
            User user = _userService.GetLoginStatus(value).Result;
            return user != null ? AutoMapper.Mapper.Map<User, UserModel>(user) : null;
        }

    }
}
